<script setup lang="jsx">
import { computed, reactive, ref } from 'vue';
import { useElementSize } from '@vueuse/core';
import { parseTime } from '@/utils';
import { SolderOndelete, SolderOnselect, SolderOnupdate, downLoadPdf } from '@/service/api/modules/erp';
import Modal from '@/components/common/modal.vue';
import Form from '@/components/common/form.vue';
import Search from './modules/search.vue';

const searchParams = ref({
  moduleNo: '',
  processId: '',
  paramCaption: '',
  wipState: '',
  pnType: '',
  modulepnTypeNo: '',
  time: ['', '']
});

const pagination = reactive({
  current: 1,
  pageSize: 200,
  showSizeChanger: true,
  pageSizeOptions: ['50', '100', '200', '300', '500'],
  showQuickJumper: true,
  showTotal: total => {
    return `共${total}条`;
  },
  total: 0,
  onChange: async (current, size) => {
    pagination.current = current;
    pagination.pageSize = size;
    getData();
  }
});

const columns = ref([
  {
    key: 'index',
    dataIndex: 'index',
    title: '序号',
    width: 100,
    align: 'center',
    checked: true
  },
  {
    key: 'inkModel',
    dataIndex: 'inkModel',
    title: '油墨型号',
    width: 130,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'inkColor',
    dataIndex: 'inkColor',
    title: '油墨颜色',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'qrCode',
    dataIndex: 'qrCode',
    title: '二维码信息',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true
  },

  {
    key: 'onTime',
    dataIndex: 'onTime',
    title: '开启时间',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.onTime == null) {
        return null;
      }
      return parseTime(record.onTime);
    }
  },
  {
    key: 'expirationTime',
    dataIndex: 'expirationTime',
    title: '失效时间',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.expirationTime == null) {
        return null;
      }
      return parseTime(record.expirationTime);
    }
  },

  {
    key: 'expirationDays',
    dataIndex: 'expirationDays',
    title: '距离失效时间',
    width: 120,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'createBy',
    dataIndex: 'createBy',
    title: '入库人',
    width: 140,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'storageTime',
    dataIndex: 'storageTime',
    title: '入库时间',
    width: 200,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.storageTime == null) {
        return null;
      }
      return parseTime(record.storageTime);
    }
  }
]);
const formList = [
  {
    type: 'input',
    key: 'inkModel',
    label: '油墨型号',
    placeholder: '请输入油墨型号',
    span: 8
  },
  {
    type: 'input',
    key: 'inkColor',

    label: '油墨颜色',
    placeholder: '请输入油墨颜色',
    span: 8
  },
  {
    type: 'input',
    key: 'qrCode',
    label: '二维码信息',
    placeholder: '请输入二维码信息',
    span: 8
  },
  {
    type: 'datePicker',
    key: 'onTime',
    label: '处理时间',
    span: 8,
    showTime: true
  },
  {
    type: 'datePicker',
    key: 'expirationTime',
    label: '失效时间',
    span: 8,
    showTime: true
  },
  {
    type: 'input',
    key: 'expirationDays',
    label: '距离失效时间',
    placeholder: '请输入距离失效时间',
    span: 8
  },
  {
    type: 'input',
    key: 'createBy',
    label: '入库人',
    placeholder: '请输入入库人',
    span: 8
  },
  {
    type: 'datePicker',
    key: 'storageTime',
    label: '入库时间',
    span: 8,
    showTime: true
  }
];
const formListqr = [
  {
    type: 'input',
    key: 'quantity',
    label: '数量',
    placeholder: '请输入数量',
    span: 24
  },
  {
    type: 'radio',
    key: 'category',
    label: '类型',
    span: 24,
    selectOptions: [
      {
        label: '塞孔油打印',
        value: '1'
      },
      {
        label: '面油打印',
        value: '2'
      }
    ]
  }
];
const tableData = ref([]);
const loading = ref(false);
const defaultExpandedRowKeys = ref([]);
const currentRowId = ref(null);
const customRow = record => {
  return {
    style: {
      background: record.id === currentRowId.value ? '#BAEAFA' : '',
      'background-color': Number(record.failureState) === 2 ? 'rgb(247, 109, 109)' : ''
    },
    onClick() {
      currentRowId.value = record.id;
    }
  };
};
function getData() {
  loading.value = true;
  SolderOnselect({
    pageSize: pagination.pageSize,
    pageNum: pagination.current,
    ...searchParams.value
  })
    .then(({ data, error }) => {
      if (!error) {
        data.forEach((item, index) => {
          item.index = index + 1;
        });
        tableData.value = data;
        pagination.total = data.total;
      }
    })
    .finally(() => {
      loading.value = false;
    });
}
const selectedRowKeys = ref([]);

function tableSelectChange(val) {
  selectedRowKeys.value = val;
}
function manualSyncing() {
  console.log(selectedRowKeys.value.length);
  if (selectedRowKeys.value.length != 1) {
    return window.$message?.error('请先选择一条数据进行同步');
  }
  const obj = tableData.value.find(person => selectedRowKeys.value[0] == person.customerErpId);
  const datas = {};
  datas.customerCode = obj.customerCode;
  SolderOnselect(datas).then(({ data, error }) => {
    if (!error) {
      window.$message?.success('手动同步成功');
      getData();
      selectedRowKeys.value = [];
    }
  });
}
const detailsVisible = ref(false);
function getRowClassName(record) {
  // console.log(record);
  // 检查每行的failureState是否为2，如果是，则返回一个类名，否则返回空字符串
  if (record.failureState == 2) {
    return 'row-red-background';
  }
  return '';
}
const upDatas = ref('');
function updata() {
  if (selectedRowKeys.value.length != 1) {
    return window.$message?.error('请先选择一条数据');
  }
  upDatas.value = tableData.value.find(person => selectedRowKeys.value[0] == person.id);
  detailsVisible.value = true;
}

function getUpdata() {
  SolderOnupdate(upDatas.value).then(({ data, error }) => {
    if (!error) {
      detailsVisible.value = false;
      upDatas.value = '';
      window.$message?.success('修改成功');
      selectedRowKeys.value = [];
      getData();
    }
  });
}
// ========================================================================
function deleteData() {
  if (selectedRowKeys.value.length == 0) {
    return window.$message?.error('请先选择一条数据');
  }
  window.$modal?.confirm({
    title: `是否确认删除数据?`,
    onOk: () => {
      delRoyiUser(delIds).then(({ data, error }) => {
        if (!error) {
          const selectData = tableData.value.filter(item => selectedRowKeys.value.includes(item.id));

          SolderOndelete(selectData).then(({ data, error }) => {
            if (!error) {
              selectedRowKeys.value = [];
              getData();
            }
          });

          window.$message?.success('删除成功!');
        } else {
          window.$message?.error('删除失败!');
        }
      });
    },
    onCancel: () => {}
  });
}
const detailsVisibleQrcode = ref(false);
function openQrCode() {
  detailsVisibleQrcode.value = true;
}
const qrDatas = ref({});
function getqrUpdata() {
  if (!qrDatas.value.quantity) {
    return window.$message?.error('请输入数量');
  }
  if (!qrDatas.value.category) {
    return window.$message?.error('请选择类型');
  }

  downLoadPdf(qrDatas.value).then(({ data, error }) => {
    detailsVisibleQrcode.value = false;
    qrDatas.value = {};
    const boldData = new Blob([data], { type: 'application/pdf' });
    const oldIframe = document.getElementById('printPdf');
    if (oldIframe) {
      oldIframe.parentNode.removeChild(oldIframe);
    }
    const iframe = document.createElement('iframe');
    iframe.style.frameborder = 'no';
    iframe.style.display = 'none';
    iframe.style.pageBreakBefore = 'always';
    iframe.setAttribute('id', 'printPdf');
    iframe.setAttribute('name', 'printPdf');
    iframe.src = window.URL.createObjectURL(boldData);
    document.body.appendChild(iframe);
    doPrint('printPdf');
    window.URL.revokeObjectURL(iframe.src);
  });
}
function doPrint(val) {
  const ordonnance = document.getElementById(val).contentWindow;
  setTimeout(() => {
    ordonnance.print();
  }, 500);
}
getData();

function search() {
  pagination.current = 1;
  getData();
}

const tableFooterRef = ref(null);
const { height } = useElementSize(tableFooterRef);

const footerHeight = computed(() => {
  return `${height.value + 20}px`;
});
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="search()" @search="search()" />
    <ACard
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="table-card flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #title>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="updata">
          <span class="ml-3px">修改</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="deleteData">
          <span class="ml-3px">删除</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="openQrCode">
          <span class="ml-3px">二维码</span>
        </AButton>
      </template>
      <template #extra>
        <TableColumnSetting v-model:columns="columns" />
      </template>
      <STable
        :columns="columns"
        :data-source="tableData"
        size="small"
        bordered
        :loading="loading"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: tableSelectChange
        }"
        :default-expanded-row-keys="defaultExpandedRowKeys"
        row-key="id"
        :custom-row="customRow"
        :default-expand-all-rows="true"
        :scroll="{ y: 'auto' }"
        :pagination="pagination"
        class="has-footer-table h-full"
        :row-height="23"
      >
        <template #footer>
          <div ref="tableFooterRef" style="display: flex; align-items: center">
            <div style="width: 20px; height: 14px; background-color: rgb(247, 109, 109)"></div>
            <span>背景为三小时内过期</span>
          </div>
        </template>
      </STable>
    </ACard>

    <Modal
      v-model:visible="detailsVisible"
      :destroy-on-close="true"
      :centered="true"
      title="阻焊油墨信息修改"
      width="1050px"
      height="550px"
    >
      <div class="event-form">
        <Form v-model:model="upDatas" :form-list="formList"></Form>
      </div>

      <template #footer>
        <div class="modal-footer">
          <AButton @click="detailsVisible = false">关闭</AButton>
          <AButton @click="getUpdata">保存</AButton>
        </div>
      </template>
    </Modal>
    <Modal
      v-model:visible="detailsVisibleQrcode"
      :destroy-on-close="true"
      :centered="true"
      title="二维码打印"
      width="550px"
      height="350px"
    >
      <div class="event-form">
        <Form v-model:model="qrDatas" :form-list="formListqr"></Form>
      </div>

      <template #footer>
        <div class="modal-footer">
          <AButton @click="detailsVisibleQrcode = false">关闭</AButton>
          <AButton @click="getqrUpdata">打印</AButton>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style lang="scss" scoped>
.row-red-background {
  background-color: rgba(244, 56, 56, 0.7) !important; /* !important 可能需要以确保覆盖其他样式 */
}
.expired {
  color: red;
  font-weight: bold;
  font-size: larger;
}

:deep(.surely-table-wrapper) {
  &.has-footer-table {
    .ant-spin-nested-loading {
      .ant-spin-container {
        .surely-table {
          height: calc(100% - 40px - v-bind('footerHeight')) !important;
        }
      }
    }
  }
}
</style>
